﻿using BW.Mes.WinForms.Common;
using BW.Mes.WinForms.Login;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace BW.Mes.WinForms.WareHouse
{
    public partial class CreateWareHouse : Form
    {
        private readonly HttpClient _httpClient;
        // 定义委托和事件
        public delegate void WareHouseAddedEventHandler(object sender, EventArgs e);
        public event WareHouseAddedEventHandler WareHouseAdded;

        // 触发事件的方法
        protected virtual void OnWareHouseAdded()
        {
            WareHouseAdded?.Invoke(this, EventArgs.Empty);
        }


        public CreateWareHouse()
        {
            InitializeComponent();
            // 初始化HttpClient
            _httpClient = new HttpClient();
            LoadWareHouseData();
            LoadWareHouseLogin();
            this.textbm.Text = "编码自动生成";
            this.textbm.ReadOnly = true;
        }



        // 仓库类型模型
        public class MoIdModel
        {
            public long Id { get; set; }
            public string MoIdName { get; set; }
        }
        // 仓管员模型
        public class UserModel
        {
            public long Id { get; set; }
            public string RealName { get; set; }
        }



        /// <summary>
        /// 仓库定义的实体
        /// </summary>
        public class WareHouseModel
        {
            /// <summary>
            /// 仓库定义编码
            /// </summary>
            public string WareHouseCoding { get; set; }
            /// <summary>
            /// 仓库定义名称
            /// </summary>
            public string WareHouseName { get; set; }
            /// <summary>
            /// 仓库定义类型 外键
            /// </summary>
            public long WareHouseStatus { get; set; }
            /// <summary>
            /// 仓库定音仓管员
            /// </summary>
            public long Loginname { get; set; }
            /// <summary>
            /// 仓库定义地址
            /// </summary>
            public string WareHouseAddress { get; set; }
            /// <summary>
            /// 仓库定义描述
            /// </summary>
            public string WareHouseDescribe { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreatedBy { get; set; }
        }



        /// <summary>
        /// 点击取消关闭弹窗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 添加到后端api方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSave_Click(object sender, EventArgs e)
        {
            
                // 从窗体控件获取数据并赋值给模型
                var product = new WareHouseModel
                {
                    WareHouseCoding = textbm.Text,
                    WareHouseName = textName.Text,
                    WareHouseStatus = (long)gridLookUpEdit1.EditValue,
                    Loginname =(long)gridLookUpEdit2.EditValue,
                    WareHouseAddress = textBoxAddress.Text,
                    WareHouseDescribe = textBoxMs.Text,
                    CreatedBy = RequestUser.InputUserName
                };

                // 调用 API 方法
                using (var client = new HttpClient())
                {
                    //设置请求地址
                    client.BaseAddress=new Uri("http://120.26.197.100:8022/");
                    //创建JSON数据（转换数据类型）
                    var json = JsonConvert.SerializeObject(product);
                    //创建请求内容
                    var  content =new StringContent(json, Encoding.UTF8, "application/json");
                    //发送POST请求
                    var response = await client.PostAsync("T3/WareHouse/CreateWareHouse", content);
                    //判断是否成功
                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("保存成功");
                        this.DialogResult = DialogResult.OK;
                         OnWareHouseAdded();

                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show("保存失败:"+response.ReasonPhrase);
                    }
                }
                textbm.Clear();
                textName.Clear();
                textBoxAddress.Clear();
                textBoxMs.Clear();
            
        }




        private void simpleButton2_Click(object sender, EventArgs e)
        {
            btnSave_Click(sender,e);
        }


        private void CreateWareHouse_Load(object sender, EventArgs e)
        {

        }


        /// <summary>
        /// 加载仓库数据
        /// </summary>
        private async void LoadWareHouseData()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T3/WareHouse/GetMoid");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<MoIdModel>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit1.Properties.DataSource = warehouses;
                        gridLookUpEdit1.Properties.DisplayMember = "MoIdName";
                        gridLookUpEdit1.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示仓库名称
                        gridLookUpEdit1.Properties.View.Columns.Clear();
                        gridLookUpEdit1.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "MoIdName",
                                Caption = "仓库类型",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit1.Properties.NullText = "请选择仓库类型";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载仓库类型数据失败: {ex.Message}", "错误");
            }
        }


        /// <summary>
        /// 加载仓管员数据
        /// </summary>
        private async void LoadWareHouseLogin()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T1/Auth/users");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pagingData"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pagingData"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<UserModel>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit2.Properties.DataSource = warehouses;
                        gridLookUpEdit2.Properties.DisplayMember = "RealName";
                        gridLookUpEdit2.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示仓库名称
                        gridLookUpEdit2.Properties.View.Columns.Clear();
                        gridLookUpEdit2.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "RealName",
                                Caption = "仓管员",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit2.Properties.NullText = "请选择仓管员";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载仓库类型数据失败: {ex.Message}", "错误");
            }
        }






    }
}
